package tech.summerly.weather.component.adapter

import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
import kotlinx.android.synthetic.main.item_daily_trend.view.*
import org.jetbrains.anko.textColor
import tech.summerly.weather.R
import tech.summerly.weather.data.bean.DailyForecast
import tech.summerly.weather.data.remote.CaiYunService
import tech.summerly.weather.util.*
import java.util.*

class DailyTrendAdapter : RecyclerView.Adapter<ViewHolder>() {

    private var forecast: DailyForecast? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = ViewHolder.createView(R.layout.item_daily_trend, parent)
        return ViewHolder(view)
    }

    fun setData(forecast: DailyForecast) {
        this.forecast = forecast
        notifyDataSetChanged()
    }

    override fun getItemCount(): Int {
        return forecast?.aqi?.size ?: 0
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) = with(holder.itemView) {
        val forecast = this@DailyTrendAdapter.forecast ?: return@with

        val temperature = forecast.temperature[position]
        val calendar = temperature.date.formatDate()


        textWeekday.text = if (calendar.isToday()) string(R.string.today) else calendar.getWeekDay()
        textDate.text = string(R.string.month_day_template, calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH))


        val skyCon = forecast.skycon[position].value
        imageSky.setImageResource(CaiYunService.SkyCon.getSkyIcon(skyCon))
        textSky.text = CaiYunService.SkyCon.getSkyConLocalString(skyCon)

        val wind = forecast.wind[position].avg
        textWind.text = wind.getWindDirection()
        textWindLevel.text = wind.getWindName()

        val aqi = forecast.aqi[position]
        val level = Aqi.from(aqi.avg.toInt())
        textAqi.text = level.localString()
        textAqi.textColor = level.color()
        textAqi.background.setTint(level.color())
        Unit
    }

}